<?php

declare(strict_types=1);

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\CustomerBrand;

class Brand extends Api
{
    // create it
    public function create()
    {
        $data = $this->request->post();
        $user = $this->request->user;

        // data['member_id'] 
        if (empty($data['member_id'])) {
            return error([], 'member_id is required');
        }

        // data['brand_id']
        if (empty($data['brand_id'])) {
            return error([], 'brand_id is required');
        }

        // 检查是否已经存在
        $where = [];
        $where['member_id'] = $data['member_id'];
        $where['brand_id'] = $data['brand_id'];
        $brand = CustomerBrand::where($where)->find();
        if ($brand) {
            return error([], '已经存在, 请勿重复添加');
        }


        $data['user_id'] = $user['id'];

        try {
            $brand = new CustomerBrand();
            $brand->save($data);
        } catch (\Exception $e) {
            return error([], $e->getMessage());
        }

        return success([], '创建成功');
    }

    // delete it
    public function delete()
    {
        $data = $this->request->post();
        $user = $this->request->user;

        // data['member_id'] 
        if (empty($data['member_id'])) {
            return error([], 'member_id is required');
        }

        // data['brand_id']
        if (empty($data['brand_id'])) {
            return error([], 'brand_id is required');
        }

        $data['user_id'] = $user['id'];

        try {
            $brand = CustomerBrand::where($data)->find();
            if ($brand) {
                $brand->delete();
            }
        } catch (\Exception $e) {
            return error([], $e->getMessage());
        }

        return success([], '删除成功');
    }
}